const { app, BrowserWindow, Menu, Tray, dialog } = require('electron')
const path = require('path')
const iconv = require('iconv-lite');
let tray;
let mainWindow;
function log(msg) {
    const time = new Date().toISOString();
    const log = `[${time}] ${msg}\n`
    const winEncoding = 'gbk' // Windows 中文系统通常使用 gbk
    const buffer = iconv.encode(log, winEncoding)
    process.stdout.write(buffer)
}
// 屏蔽安全警告
// ectron Security Warning (Insecure Content-Security-Policy)
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
const iconPath = process.platform === 'win32' ? path.join(__dirname, '../public', 'logo.ico') : path.join(__dirname, '../public', 'logo.png');
// 执行createWindow创建窗口
const createWindow = () => {
    const win = new BrowserWindow({
        width: 1200,
        height: 1900,
        minWidth: 800,
        minHeight: 1600,
        title: 'SF桌面端',
        icon: iconPath,
        webPreferences: {
            devTools: true,
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true
        }
    });
    //开发者模式

    win.webContents.openDevTools();
    if (process.env.VITE_DEV_SERVER_URL) {
        win.loadURL(process.env.VITE_DEV_SERVER_URL);
    } else {
        const url = require('url');
        // ✅ 正确加载打包后的 index.html
        const indexPath = path.join(__dirname, '..', 'dist', 'index.html')

        // 方式一：使用 loadFile（推荐）
        win.loadFile(indexPath)
    }
    // 添加以下代码
    win.webContents.on('did-finish-load', () => {
        win.webContents.openDevTools()
        log('开发者工具已打开')
    })
    win.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
        log('页面加载失败:', errorDescription)
    })
    createTray(iconPath);
    const menu = Menu.buildFromTemplate([
        {
            label: '简介',
            submenu: [
                {
                    label: '简介',
                    click() {
                        dialog.showMessageBox(mainWindow, {
                            type: 'info',
                            title: '简介',
                            message: '桌面端上飞院项目',
                            buttons: ['确定']
                        });
                    }
                }
            ]
        },
        {
            label: '试用人员',

            submenu: [
                {
                    label: '试用人员',
                    click() {
                        dialog.showMessageBox(mainWindow, {
                            type: 'info',
                            title: '试用人员',
                            message: '粥粥粥',
                            buttons: ['确定']
                        });
                    }
                }
            ]
        }
    ])
    Menu.setApplicationMenu(menu)
}
function createTray(iconPath) {
    try {
        if (tray) {
            return;
        }
        tray = new Tray(iconPath);
        const contextMenu = Menu.buildFromTemplate([
            {
                label: '显示窗口',
                click: () => {
                    if (mainWindow) {
                        // 若窗口存在，不管是否销毁，都尝试显示
                        if (mainWindow.isDestroyed()) {
                            // 若窗口已销毁，重新创建
                            createWindow();
                        } else {
                            // 若窗口未销毁，直接显示
                            mainWindow.show();
                        }
                    } else {
                        // 若窗口不存在，重新创建
                        createWindow();
                    }
                }
            },
            {
                label: '退出',
                click: () => {
                    app.isQuitting = true;
                    app.quit();
                }
            }
        ]);
        tray.setContextMenu(contextMenu);
        tray.on('click', () => {
            if (mainWindow) {
                // 若窗口存在，不管是否销毁，都尝试显示
                if (mainWindow.isDestroyed()) {
                    // 若窗口已销毁，重新创建
                    createWindow();
                } else {
                    // 若窗口未销毁，直接显示
                    mainWindow.show();
                }
            } else {
                // 若窗口不存在，重新创建
                createWindow();
            }
        });

    } catch (error) {
        log(`创建托盘图标时出错: ${error.message}`);
    }
}
// Electron 会在初始化后并准备
app.whenReady().then(() => {
    createWindow()
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
})

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})
